package com.daydayup.learn;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
public class CouponServiceImpl implements CouponService {

    /**
     * 下发优惠券的数量
     */
    public static final Integer COUPON_NUMBER = 50;

    @Resource
    private ThreadPoolTaskExecutor threadPool;

    /**
     * 执行下发逻辑
     */
    @Override
    public void batchTaskAction() {
        // 1、模拟要下发的50条优惠券
        List<String> coupons = new ArrayList<>(COUPON_NUMBER);
        for (int i = 0; i < COUPON_NUMBER; i++) {
            coupons.add("优惠券---" + i);
        }
        // 2 创建CountDownLatch,构造器参数是任务数量
        CountDownLatch countDownLatch = new CountDownLatch(coupons.size());
        long startTime = System.currentTimeMillis();
        try {
            // 3 将优惠券集合逐条发送进线程池高并发处理
            for (String coupon : coupons) {
                threadPool.execute(() -> {
                    try {
                        // 4 线程池处理下发业务逻辑
                        System.out.println(String.format("【%s】发生成功：", coupon));
                    } finally {
                        // 5 发送一个少一个任务,计数减少一个
                        countDownLatch.countDown();
                    }
                });
            }
            // 6 阻塞当前发送完毕后,方法才能继续向下走
            countDownLatch.await();
        } catch (Exception e){
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("----任务处理完毕 costTime:"+(endTime-startTime)+"毫秒");
    }
}
